<template>
  <view class="container">
    <map ref="mapRef" class="map" :longitude="longitude" :latitude="latitude" :scale="scale" :markers="markers"
      :polyline="polyline" :show-location="showLocation" @regionchange="onRegionChange" @markertap="onMarkerTap">
    </map>
	
    <!-- 控制按钮容器 -->
    <view class="controls">
      <!-- 独立定位按钮 -->
      <button class="control-btn locate-btn" @click="locateToCurrentPosition">
        <image src="/static/images/当前位置.png" mode="aspectFit"></image>
      </button>

      <!-- 列表跳转按钮 -->
      <button class="control-btn list-btn" @click="navigateToList">
        <image src="/static/images/list.png" mode="aspectFit"></image>
      </button>
    </view>

    <!-- 修改位置信息卡片，使用绝对定位展示气泡 -->
    <view class="location-info" v-if="selectedLocation" :style="{ top: bubbleTop + 'px', left: bubbleLeft + 'px' }">
      <text class="info-item">设备名称: {{ selectedLocation.devicename }}</text>
      <text class="info-item">电池健康程度: {{ selectedLocation.cell }}%</text>
      <text class="info-item">电量: {{ selectedLocation.electric }}%</text>
    </view>
  </view>
  
  <!-- 滑动弹窗 -->
  <view class="swipepopup-box">
  	<SwipePopup
  		:visible="popupVisible" 
  		:showConfirm="true"
  		@close="popupVisible = false"
  		@confirm="onConfirm"
  	>
		<view class="search-box">
			<uni-search-bar 
			 placeholder="搜索"
			 :radius="16"
			 bgColor="#f8f8f8"
			 @confirm="handleSearch"
			 @clear="handleClear"
			 >
			</uni-search-bar>
		</view>
		
		<view v-if="showOnlyPowerbankList || showOnlyAudioList" class="back-btn-container">
		  <view class="back-btn" @click="goBackToList">
			<image src="/static/images/back.png" mode="aspectFit"></image>
			<text>返回</text>
		  </view>
		</view>
		
  		<view class="popup-content">
			
  		  <!-- 原内容列表，根据状态决定是否显示 -->
  		  <view class="content-list" v-if="!showOnlyPowerbankList && !showOnlyAudioList">
  		    <view class="content-item" @click="showOnlyPowerbankList = true">
  		      <view class="item-img">
  		        <image src="/static/images/charge_pal_img.png" mode=""></image>
  		      </view>
  		      <text class="item-text">充电宝列表</text>
  		    </view>
  		    <view class="content-item" @click="showOnlyAudioList = true">
  		      <view class="item-img">
  		        <image src="/static/images/录音 (1).png" mode=""></image>
  		      </view>
  		      <text class="item-text">录音列表</text>
  		    </view>
  		  </view>
  		  <!-- 充电宝列表，根据状态决定是否显示 -->
  		  <scroll-view class="powerbank-list" v-else-if="showOnlyPowerbankList">
  		    <view
  		      v-for="(item,index) in powerbankList"
			  :key="index"
  		      class="powerbank-item">
  		      <!-- 图片容器 -->
  		      <view class="item-img">
  		        <image src="/static/images/power_bank_img.png" mode="aspectFill"></image> 
  		      </view>
  		      <view class="device-info">
  		        <view class="status-value"><text class="name">设备昵称：</text><text class="value">{{ item.devicename }}</text></view>
				<view class="status-value"><text class="name">电量：</text><text class="value">{{ item.electric }}%</text></view>
				<view class="status-value"><text class="name">温度：</text><text class="value">{{ item.temperature }}%</text></view>
				<view class="status-value"><text class="name">湿度：</text><text class="value">{{ item.humidity }}%</text></view>
				<view class="status-value"><text class="name">电池健康度：</text><text class="value">{{ item.cell }}%</text></view>
  		      </view>
  		    </view>
			  
			<!-- 右下角按钮 -->
				  <view class="float-button" @click="handleAddPowerBank()">
				    <uni-icons type="plus" size="28" color="#fff"></uni-icons>
				  </view>
  		  </scroll-view>
		  
		  <scroll-view class="audio-list" v-else-if="showOnlyAudioList">
		      <view
		        v-for="(audio, index) in audioList"
		        class="audio-item"
		        :class="{ 'active-audio': activeIndex === index }"
				@click="naviRecordDetailTo"
		      >
		        <view class="audio-content">
                  <view class="audio-header">
                    <view class="audio-name">{{ audio.name }}</view>
                    <view class="time-display">
                      {{ formatTime(audio.currentTime) }} / {{ formatTime(audio.duration) }}
                    </view>
                  </view>
                  
                  <view class="play-btn" @click.stop="togglePlayPause(index)">
                    <image 
                      :src="audio.isPlaying ? '/static/images/pause.png' : '/static/images/play.png'" 
                      class="play-icon" 
                    />
                  </view>
                </view>
                
                <view :class="['dropDown', {'expanded': audio.isPlaying}]">
                  <view :class="['progress-bar-container', {'bar-container': audio.isPlaying}]">
                    <slider
                      v-if="audio.isPlaying"
                      :block-size="16"
                      :value="audio.progress" 
                      @change="handleProgressChange(index, $event)" 
                      @touchstart="handleProgressTouchStart(index)" 
                      @touchmove="handleProgressTouchMove(index, $event)"
                      @touchend="handleProgressTouchEnd(index)"
                      min="0" 
                      max="100"
                      activeColor="#FF4949" 
                      backgroundColor="#eee"
                    />
                  </view>
                </view>
		      </view>
		    </scroll-view>
  		</view>
  	</SwipePopup>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { getdata } from '@/api/common.js'
import { onLoad, onShow } from "@dcloudio/uni-app";
import SwipePopup from '@/components/SwipePopup.vue'
import { getFindDeviceByUid,getFfileQuery } from '@/api/common.js';

// 地图状态
const mapRef = ref(null)
const longitude = ref(115.545009)
const latitude = ref(38.86899)
const scale = ref(16)
const markers = ref([])
const polyline = ref([])
const showLocation = ref(false)
const selectedLocation = ref(null)
const powerBankLocation = ref(null)
const datas = ref([])
const bubbleTop = ref(0)
const bubbleLeft = ref(0)

const showOnlyPowerbankList = ref(false)
const showOnlyAudioList = ref(false); 


// 播放控制状态
const activeIndex = ref(-1);
let currentAudioCtx = null;
let currentItemIndex = -1;
let isDragging = false;

// 充电宝列表
const powerbankList = ref([]);
// const powerbankList = ref([
//   {
//     devicename: '充电宝',
//     electric: 85,
//     temperature: 25,
//     humidity: 45,
//     cell: 92
//   },
//   {
//     devicename: '充电宝',
//     electric: 85,
//     temperature: 25,
//     humidity: 45,
//     cell: 92
//   },
//   {
//     devicename: '充电宝',
//     electric: 85,
//     temperature: 25,
//     humidity: 45,
//     cell: 92
//   },
// ]);

// 录音列表数据
const audioList = ref([
  {
    id: 1,
    name: '录音1',
    duration: 180, // 3分钟
    date: '2025-06-05',
    url: 'https://example.com/audio1.mp3', // 示例音频地址
    isPlaying: false,
    currentTime: 0,
    progress: 0,
    isLoading: false
  },
  {
    id: 2,
    name: '录音2',
    duration: 270, // 4分30秒
    date: '2025-06-04',
    url: 'https://example.com/audio2.mp3',
    isPlaying: false,
    currentTime: 0,
    progress: 0,
    isLoading: false
  },
]);

onShow(() => {
  const userInfo = uni.getStorageSync("userInfo")?.id

  getdata(userInfo).then((res) => {
    if (res.code === 200 && res.data && res.data.length > 0) {
      datas.value = res.data[0]
      powerBankLocation.value = {
        id: 1,
        longitude: 115.545009,
        latitude: 38.86899,
        title: res.data[0].devicename,
        iconPath: '/static/images/chongdianbao.png',
        width: 50,
        height: 50,
        anchor: { x: 0.5, y: 1 },
      }
      if (powerBankLocation.value) {
        markers.value.push(powerBankLocation.value)
      }
    } else {
      console.log('获取充电宝位置数据失败，code 不为 200:', res)
    }
  }).catch((err) => {
    console.error('调用 getdata 接口失败:', err)
  })
  showPopup()
})

onLoad(async () => {
 const uid = uni.getStorageSync('userInfo')?.id;
   if (!uid) {
     uni.showToast({ title: '用户信息缺失', icon: 'none' });
     return;
   }
 
   getFindDeviceByUid({ uid })
     .then((res) => {
       if (res.code === 200) {
         powerbankList.value = res.data;
         console.log('设备列表更新:', res.data);
       } else {
         uni.showToast({ title: '获取设备失败', icon: 'none' });
       }
     })
     .catch((error) => {
       console.error('网络请求失败:', error);
     });

});

// 
const loadDeviceList = () => {
  const uid = uni.getStorageSync('userInfo')?.id;
  if (!uid) {
    uni.showToast({ title: '用户信息缺失', icon: 'none' });
    return;
  }

  getFindDeviceByUid({ uid })
    .then((res) => {
      if (res.code === 200) {
        powerbankList.value = res.data;
        console.log('设备列表更新:', res.data);
      } else {
        uni.showToast({ title: '获取设备失败', icon: 'none' });
      }
    })
    .catch((error) => {
      console.error('网络请求失败:', error);
    });
};


const popupVisible = ref(false);

const showPopup = () => {
  popupVisible.value = true;
};

const onConfirm = () => {
  uni.showToast({
    title: '操作成功',
    icon: 'success'
  });
};

const onMarkerTap = (e) => {
  const markerId = e.markerId
  selectedLocation.value = {
    cell: datas.value.cell,
    devicename: datas.value.devicename,
    electric: datas.value.electric,
    humidity: datas.value.humidity
  }
  mapRef.value.convertToScreenLocation({
    longitude: powerBankLocation.value.longitude,
    latitude: powerBankLocation.value.latitude,
    success: (res) => {
      bubbleTop.value = res.y + 25
      bubbleLeft.value = res.x - 100
    },
    fail: (err) => {
      console.error('坐标转换失败:', err)
    }
  })
}

const locateToCurrentPosition = () => {
  let myLongitude = null;
  let myLatitude = null;
  if (!powerBankLocation.value) {
    myLongitude = 115.545009 - 0.0003;
    myLatitude = 38.86899;
  }else {
    myLongitude = powerBankLocation.value.longitude - 0.0003
    myLatitude = powerBankLocation.value.latitude
  }
  longitude.value = myLongitude
  latitude.value = myLatitude
  scale.value = 18

  const currentMarkerIndex = markers.value.findIndex(m => m.id === 2)
  if (currentMarkerIndex === -1) {
    markers.value.push({
      id: 2,
      longitude: myLongitude,
      latitude: myLatitude,
      title: '我的位置',
      iconPath: '/static/images/dingwei.png',
      width: 50,
      height: 50,
      anchor: { x: 0.5, y: 1 },
    })
  } else {
    markers.value[currentMarkerIndex] = {
      id: 2,
      longitude: myLongitude,
      latitude: myLatitude,
      title: '我的位置',
      iconPath: '/static/images/dingwei.png',
      width: 50,
      height: 50,
      anchor: { x: 0.5, y: 1 },
    }
  }

  uni.showToast({
    title: '定位成功',
    icon: 'success'
  })
}

// 地图放大缩小
const zoomIn = () => { if (scale.value < 20) scale.value += 1 }
const zoomOut = () => { if (scale.value > 3) scale.value -= 1 }

const onRegionChange = (e) => { console.log('地图区域变化', e) }

const navigateToLocation = () => {
  if (!selectedLocation.value) return
  uni.openLocation({
    longitude: selectedLocation.value.longitude,
    latitude: selectedLocation.value.latitude,
    name: selectedLocation.value.name,
    address: selectedLocation.value.address,
  })
}


// 播放控制相关方法
const togglePlayPause = (index) => {
  const item = audioList.value[index];
  if (item.isPlaying) {
    item.isPlaying = false;
    currentAudioCtx.pause();
  } else {
    item.isPlaying = true;
    currentAudioCtx.play();
  }
};

const playAudio = (index) => {
  stopCurrentAudio();
  const item = audioList.value[index];
  if (!item.url) return;
  
  currentItemIndex = index;
  activeIndex.value = index;
  item.isPlaying = true;
  
  currentAudioCtx = uni.createInnerAudioContext();
  currentAudioCtx.src = item.url;
  item.isLoading = true;
  
  currentAudioCtx.onCanplay(() => {
    item.duration = Math.floor(currentAudioCtx.duration);
    item.isLoading = false;
    currentAudioCtx.play();
  });
  
  currentAudioCtx.onTimeUpdate(() => {
    if (item.duration === 0) return;
    const progress = (currentAudioCtx.currentTime / item.duration) * 100;
    item.progress = Math.max(0, Math.min(100, Math.floor(progress)));
    item.currentTime = Math.floor(currentAudioCtx.currentTime);
  });
  
  currentAudioCtx.onEnded(() => {
    stopCurrentAudio();
  });
  
  currentAudioCtx.onError((err) => {
    console.error('音频播放错误:', err);
    item.isPlaying = false;
    item.isLoading = false;
    stopCurrentAudio();
  });
};

const stopCurrentAudio = () => {
  if (currentAudioCtx) {
    currentAudioCtx.pause();
    currentAudioCtx.destroy();
    currentAudioCtx = null;
  }
  currentItemIndex = -1;
  activeIndex.value = -1;
  audioList.value.forEach(item => {
    item.isPlaying = false;
    item.progress = 0;
    item.currentTime = 0;
  });
};

const handleProgressTouchStart = (index) => {
  isDragging = true;
  const item = audioList.value[index];
  if (currentItemIndex === index && currentAudioCtx) {
    currentAudioCtx.pause();
  }
};

const handleProgressTouchMove = (index, e) => {
  if (!isDragging) return;
  const item = audioList.value[index];
  if (currentItemIndex === index && item.duration) {
    const percent = Math.max(0, Math.min(100, e.detail.value));
    item.progress = percent;
    const newTime = (percent / 100) * item.duration;
    currentAudioCtx?.seek(newTime);
  }
};

const handleProgressTouchEnd = (index) => {
  isDragging = false;
  const item = audioList.value[index];
  if (currentItemIndex === index && currentAudioCtx) {
    currentAudioCtx.play();
  }
};

const handleProgressChange = (index, e) => {
  if (isDragging) return;
  const item = audioList.value[index];
  if (currentItemIndex === index && item.duration && currentAudioCtx) {
    const percent = Math.max(0, Math.min(100, e.detail.value));
    const newTime = (percent / 100) * item.duration;
    currentAudioCtx.seek(newTime);
  }
};

const formatTime = (seconds) => {
  if (isNaN(seconds) || seconds === 0) return '00:00';
  const min = Math.floor(seconds / 60).toString().padStart(2, '0');
  const sec = Math.floor(seconds % 60).toString().padStart(2, '0');
  return `${min}:${sec}`;
};

// 返回按钮
const goBackToList = () => {
  showOnlyPowerbankList.value = false;
  showOnlyAudioList.value = false;
};

onUnmounted(() => {
  stopCurrentAudio();
});

onMounted(() => {
  if (powerBankLocation.value) {
    markers.value.push(powerBankLocation.value)
  }
})

const navigateToList = () => {
  uni.navigateTo({
    url: '/pages/power_bank_list/power_bank_list',
    animationType: 'slide-in-right',
  })
}

const naviRecordDetailTo = () =>{
	uni.navigateTo({
		url:'/pages/voice_text/voice_text'
	})
}

// 新增充电宝
const handleAddPowerBank = () =>{
	uni.navigateTo({
		url:`/pages/qrCode/index`
	})
}
</script>

<style lang="scss" scoped>
$primary-color: #2197ef;
$secondary-color: #6B8DD6;

.container {
  width: 100%;
  height: calc(100vh - 200rpx); /* 减去弹窗高度 */
  position: relative;

  .map {
    width: 100%;
    height: 100%;
  }

  .controls {
    position: absolute;
    right: 30rpx;
    bottom: 200rpx;
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    z-index: 200;

    .control-btn {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.12);
      display: flex;
      justify-content: center;
      align-items: center;
      transition: all 0.2s;

      &:active {
        transform: scale(0.9);
        opacity: 0.8;
      }

      image {
        width: 50rpx;
        height: 50rpx;
      }

      // 定位按钮样式
      &.locate-btn {
        background: $primary-color;

        image {
          filter: brightness(0) invert(1); // 图标反白
        }
      }

      // 列表按钮样式
      &.list-btn {
        background: #fff;
      }
    }
  }

  .location-info {
    position: absolute;
    background-color: #fff;
    border-radius: 8rpx;
    padding: 16rpx 24rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
    z-index: 200; // 提高层级，避免被其他元素遮挡
    min-width: 200rpx;

    // 新增气泡箭头样式
    &::before {
      content: '';
      position: absolute;
      top: -10px;
      left: 50%;
      transform: translateX(-50%);
      border-width: 0 10px 10px 10px;
      border-style: solid;
      border-color: transparent transparent #fff transparent;
    }

    .info-item {
      display: block;
      font-size: 24rpx;
      color: #333;
      line-height: 1.5;
    }
  }
}

.swipepopup-box{
	position: fixed;
	bottom: 0;
	height: 200rpx;
	z-index: 200;
	
	.back-btn-container {
	  position: absolute;
	  top: 20rpx;
	  left: 30rpx;
	  z-index: 10;
	}

	.back-btn {
	  display: flex;
	  align-items: center;
	  background-color: rgba(255, 255, 255, 0.8);
	  padding: 10rpx 20rpx;
	  border-radius: 30rpx;
	  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	  
	  image {
		width: 30rpx;
		height: 30rpx;
		margin-right: 10rpx;
	  }
	  
	  text {
		font-size: 26rpx;
		color: #333;
	  }
	}
	
	.popup-content{
		width: 100%;
		.content-list{
			 display: flex;
			  gap: 10rpx;
			  .content-item{
				  padding: 20rpx 45rpx;
				  .item-img{
					width: 80rpx;
					height: 80rpx;
					padding: 20rpx;
					border-radius: 16rpx;
					background-color: #f0f0f0;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					cursor: pointer;
					image{
						width: 100%;
						height: 100%;
					}
				  }
				 .item-text{
					font-size: 28rpx;
				    color: #333;
				 }
			  }
		}
		.powerbank-list {
			position: relative;
		  .powerbank-item {
		    background: #ffffff;
		    border-radius: 24rpx;
		    padding: 20rpx;
		    margin-bottom: 24rpx;
		    display: flex;
		    align-items: flex-start;
		    box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.06);
		    transition: all 0.2s;
		
		    .item-img {
		      width: 200rpx;
		      height: 200rpx;
		      margin-right: 20rpx;
		      border-radius: 12rpx;
		      overflow: hidden; 
		      display: flex;
		      align-items: center;
		      justify-content: center;
		
		      image {
		        width: 100%;
		        height: 100%;
		      }
		    }
		
		    .device-info {
		      flex: 1;
		      color: #070707;
		
		      .status-value {
		        font-size: 26rpx;
		        display: flex; 
		        flex: 1;
		
		        .name {
		          display: block;
		          flex: 1;
		        }
		
		        .value {
		          flex: 1;
		        }
		      }
		    }
		  }
		 .float-button {
		 	  position: absolute;
			  top: 50rpx;
			  right: 0;
		 	  width: 100rpx;
		 	  height: 100rpx;
		 	  background: #2197ef;
		 	  border-radius: 50%;
		 	  display: flex;
		 	  align-items: center;
		 	  justify-content: center;
		 	  box-shadow: 0 6rpx 12rpx rgba(33, 151, 239, 0.3);
		 	  z-index: 999;
		 	  transition: all 0.2s;
		 	  
		 	  &:active {
		 	    transform: scale(0.9);
		 	    opacity: 0.8;
		 	  }
		 	}
		}
		// 录音列表播放控制样式
		.audio-list {
		  .audio-item {
		    padding: 20rpx;
		    border-bottom: 1rpx solid #eee;
		    transition: all 0.3s ease;
		    
		    &.active-audio {
		      background-color: rgba(0, 122, 255, 0.05);
		      transform: translateY(-2rpx);
		    }
		    
		    .audio-content {
		      display: flex;
		      flex-direction: row;
		      justify-content: space-between;
		      align-items: center;
		      padding-bottom: 16rpx;
		    }
		    
		    .audio-header {
		      display: flex;
		      flex-direction: column;
		      gap: 8rpx;
		    }
		    
		    .audio-name {
		      font-size: 30rpx;
		      font-weight: bold;
		      color: #333;
		      max-width: 400rpx;
		      white-space: nowrap;
		      overflow: hidden;
		      text-overflow: ellipsis;
		    }
		    
		    .time-display {
		      font-size: 24rpx;
		      color: #999;
		    }
		    
		    .play-btn {
		      display: flex;
		      justify-content: center;
		      align-items: center;
		      width: 70rpx;
		      height: 70rpx;
		      // background-color: #d3d3d3;
		      // background: linear-gradient(135deg, #007AFF 0%, #34AADC 100%);
		      border-radius: 50%;
		      box-shadow: 0 6rpx 16rpx rgba(0, 122, 255, 0.3);
		      transition: all 0.3s ease;
		      
		      .play-icon {
		        width: 36rpx;
		        height: 36rpx;
		      }
		      
		      &:active {
		        transform: scale(0.95);
		        box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.4);
		      }
		    }
		  }
		  
		  // 进度条动画效果
		  .dropDown {
		    height: 0;
		    margin-top: 16rpx;
		    overflow: hidden;
		    transition: height 0.3s ease-in-out;
		  }
		  
		  .dropDown.expanded {
		    height: 50rpx;
		  }
		  
		  .progress-bar-container {
		    transform-origin: left center;
		    transition: transform 0.3s ease-in-out;
		    transform: scaleX(0);
		  }
		  
		  .progress-bar-container.bar-container {
		    transform: scaleX(1);
		  }
		  
		  // 滑块样式（深度选择器）
		  :deep(.uni-slider) {
		    height: 8rpx;
		    margin-top: 10rpx;
		  }
		  
		  :deep(.uni-slider-track) {
		    height: 8rpx;
		    border-radius: 4rpx;
		  }
		  
		  :deep(.uni-slider-active-track) {
		    background-color: #FF4949;
		    height: 8rpx;
		    border-radius: 4rpx;
		  }
		  
		  :deep(.uni-slider-handle) {
		    width: 28rpx;
		    height: 28rpx;
		    background-color: #FF4949;
		    border-radius: 50%;
		    margin-top: -10rpx;
		    box-shadow: 0 2rpx 8rpx rgba(255, 73, 73, 0.5);
		  }
		  
		  :deep(.uni-slider-handle::after) {
		    display: none;
		  }
		}
		
		// 滑动弹窗内的录音列表样式（补充）
		.swipepopup-box {
		  .popup-content {
		    .audio-list {
		      .audio-item {
		        padding: 20rpx;
		        border-bottom: 1rpx solid #f5f5f5;
		        
		        &:last-child {
		          border-bottom: none;
		        }
		        
		        .audio-name {
		          font-size: 28rpx;
		          font-weight: 500;
		          color: #333;
		        }
		        
		        .audio-info {
		          font-size: 24rpx;
		          color: #999;
		          margin-top: 4rpx;
		        }
		      }
		    }
		  }
		}
	}
	
}
</style>
